// components/share-image/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    detail: Object
  },

  /**
   * 组件的初始数据
   */
  data: {
    unit: 1, // 比例
    saveImageAuth: '1', // 权限
    tempFilePath: '', // 临时图片地址
  },
  lifetimes: {
    attached() {
      // 检查授权权限
      this.checkSaveImageAuth();
      // //获取用户设备信息，屏幕宽度
      wx.getSystemInfo({
        success: res => {
          console.log('getSystemInfo', res)
          this.setData({
            unit: res.windowWidth / 750 * 0.8,
            ratio: res.pixelRatio
          })
        }
      })
      this.drawCanvas()
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 封装的下载图片函数
    downLoadImage(url) {
      return new Promise((resolve, reject) => {
        wx.getImageInfo({
          src: url,
          success(res) {
            resolve(res.path)
          },
          fail(err) {
            reject(err)
          },
          complete() {
            console.log('complete')
          }
        })
      })
    },
    // 封装的下载云存储文件函数
    downLoadCloudFile(id) {
      return new Promise((resolve, reject) => {
        wx.cloud.downloadFile({
          fileID: id,
          success: res => {
            // 返回临时文件路径
            resolve(res.tempFilePath)
          },
          fail: err => {
            console.log('err', err)
          }
        })
      })
    },
    bindOpenSetting(e) {
      let _this = this
      wx.openSetting({
        success(res) {
          if (res.authSetting['scope.writePhotosAlbum']) {
            _this.saveImage()
          } else {
            wx.showToast({
              title: '请授权保存相册权限，才能为您生成分享图',
              icon: 'none'
            })
          }
        }
      })
      console.log('检查权限', e)
    },
    // 检查用户授权权限
    checkSaveImageAuth() {

      let _this = this
      wx.getSetting({
        success(res) {
          console.log('检查用户授权权限', res)
          let auth = ''
          // 有权限
          if (res.authSetting['scope.writePhotosAlbum'] === true) {
            console.log('2')
            auth = '2'
            // 无权限
          } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
            console.log('1')
            auth = '1'
          } else {
            // 未设置
            console.log('0')
            auth = '0'
          }
          _this.setData({
            saveImageAuth: auth
          })
        }
      })
    },
    drawCanvas() {
      wx.showLoading({
        title: '生成图片中',
        icon: 'none'
      });
      let detail = this.properties.detail;
      let ctx = wx.createCanvasContext('shareCanvas', this)
      let titleImage = this.downLoadImage('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564939798200&di=8eb01e28ccecbc2915e8f01c7de8c033&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fc0e346e2038c9dbbe19454fb6f1f53c6ffa9eac14854f-SyL8wk_fw658');
      // let productImage = this.downLoadImage(detail.img);
      let productImage = this.downLoadImage('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564939578563&di=111f88601bc69efdf1728a89170edc48&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F057c50ab3dc879fe71f73661d8b7bff8b8034b1f28907-LWqMS5_fw658');
      let erCodeImage = this.downLoadImage('https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1969939437,3569890296&fm=26&gp=0.jpg');
      Promise.all([titleImage, productImage, erCodeImage]).then(imgs => {
        console.log('imgs', imgs)
        // 全部图片下载成功
        let bgWidth = 750;
        let bgHeight = 1.5 * 750;
        // 绘制白底背景
        ctx.setFillStyle('#fff')
        ctx.fillRect(0, 0, bgWidth, bgHeight)
        // ctx.stroke()
        console.log('全部图片下载成功')
        // 绘制顶部标题图片
        let titleOffLeft = (750 - 652) / 2;
        let titleOffTop = 60;
        let titleWidth = 652;
        let titleHeight = 37;
        // todo 偏移量需要再处理一下
        ctx.drawImage(imgs[0], titleOffLeft, titleOffTop, titleWidth, titleHeight);
        // 绘制产品图片
        let productOffLeft = 30;
        let productOffTop = 155;
        let productWidth = 690;
        let productHeight = 380;
        ctx.drawImage(imgs[1], productOffLeft, productOffTop, productWidth, productHeight)
        // 绘制矩形边框
        ctx.lineWidth = 1;
        ctx.strokeStyle = '#ccc';
        ctx.rect(30, 156, 690, 670);
        ctx.stroke();
        // 绘制标题
        ctx.setFillStyle('#333') // 文字颜色

        ctx.font = `${32}px PingFang`; // 文字字号

        let title1 = detail.title;
        let title2 = '';
        if (title1.length > 40) {
          title2 = title1.substring(20, 39) + '...'
        } else if (title1.length > 20) {
          title2 = title1.substring(20)
        }
        title1 = title1.substring(0, 20)
        let textWidth = ctx.measureText(title1).width;
        let canvasWidthNoPadding = 750 - 56 * 2;
        ctx.fillText(title1, 56, 595)
        ctx.fillText(title2, 56, 630)
        // 绘制副标题
        ctx.setFillStyle('#ccc');
        ctx.font = `28px PingFang`;
        let subTitle = detail.subTitle;
        if (subTitle.length > 23) {
          subTitle = subTitle.substring(0, 22) + '...'
        }
        ctx.fillText(subTitle, 56, 695)
        // 绘制价格
        let priceIcon = '¥ ';
        let price = String(detail.price); // 价格
        let priceTail = ' /人起'
        ctx.font = '28px PingFang';

        ctx.setFillStyle('#ff5346');
        ctx.fillText(priceIcon, 56, 770 );
        let offsetPriceIcon = ctx.measureText(priceIcon).width;
        ctx.font = '36px PingFang';
        ctx.fillText(price, (56 + offsetPriceIcon), 770 );
        let offsetPrice = ctx.measureText(price).width;
        console.log('offsetPrice', offsetPrice)
        ctx.font = '28px PingFang';
        ctx.setFillStyle('#ccc');
        ctx.fillText(priceTail, (56 + offsetPriceIcon + offsetPrice), 770 );
        // 绘制旅游顾问信息
        let saleTitle = '您的专属旅游顾问';
        let saleName = detail.saleName;
        let salePhone = String(detail.salePhone);
        ctx.font = '24px PingFang';
        ctx.fillText(saleTitle, 30 , 930 );
        ctx.setFillStyle('#666');
        ctx.fillText(saleName, 30, 972 );
        let saleNameWidth = ctx.measureText(saleName).width;
        ctx.fillText(salePhone, 50 + saleNameWidth, 972 );
        // 绘制供应商
        ctx.setFillStyle('#ff7800');
        let supplierName = `供应商：${detail.supplier}`;
        let supplierNameWidth = ctx.measureText(supplierName).width;
        ctx.fillText(supplierName, 50, 1036 );
        this.roundRect(ctx, 30, 1006 , (supplierNameWidth + 40), 40, 20)
        // 绘制二维码
        let ercodeDesc = '长按识别二维码下单';
        ctx.setFillStyle('#bbb');
        ctx.font = '22px PingFang';
        let ercodeDescWidth = ctx.measureText(ercodeDesc).width;
        let offsetErCode = (750 - 30) - ercodeDescWidth;
        ctx.fillText(ercodeDesc, offsetErCode, 1078);
        console.log('imgs', imgs[2])
        ctx.drawImage(imgs[2], 540 , 860, 165, 165)
        // ctx.draw();
        ctx.draw(true, () => {
          wx.hideLoading();
          wx.showLoading({
            title: '保存中',
            icon: 'none'
          })
          let _this = this;
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            canvasId: 'shareCanvas',
            quality: 1.0,
            fileType: 'jpg',
            success(res) {
              console.log('生成图片成功')
              console.log('res', res)
              _this.setData({
                tempFilePath: res.tempFilePath
              })
              wx.hideLoading()
            },
            fail(err) {
              console.log('err', err)
              wx.showToast({
                title: '图片生成失败',
                icon: 'none',
              })
              _this.triggerEvent('complete');
            },
            complete() {
              
            }
          }, _this)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    onClose() {
      wx.hideLoading();
      this.triggerEvent('complete');
    },
    // 保存图片
    saveImage() {
      let _this = this;
      let tempFilePath = this.data.tempFilePath;
      if (!tempFilePath) {
        wx.showToast({
          title: '图片生成失败',
          icon: 'none',
        })
        return;
      }
      wx.saveImageToPhotosAlbum({
        filePath: tempFilePath,
        success() {
          wx.showToast({
            title: '已保存到相册，您可将图片分享到朋友圈',
            icon: 'none'
          })
          _this.triggerEvent('complete');
        },
        fail() {
          wx.showToast({
            title: '图片保存失败',
            icon: 'none',
          })
          _this.checkSaveImageAuth()
        },
        complete() {
          // wx.hideLoading();
        }
      })
    },
    // 绘制圆角矩形
    roundRect(ctx, x, y, w, h, r) {
      // ctx.save();
      if (w < 2 * r) {
        r = w / 2;
      }
      if (h < 2 * r) {
        r = h / 2;
      }
      ctx.beginPath();
      ctx.setStrokeStyle('#ff7800');
      ctx.setFillStyle('transparent')
      ctx.setLineWidth(0.5);
      ctx.moveTo(x + r, y);
      ctx.arcTo(x + w, y, x + w, y + h, r);
      ctx.arcTo(x + w, y + h, x, y + h, r);
      ctx.arcTo(x, y + h, x, y, r);
      ctx.arcTo(x, y, x + w, y, r);
      ctx.stroke();
      ctx.closePath();
    },
  },

})